package com.itheima.Filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class CheckLoginFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        /*0.禁止远程访问
        获得接入的IP
        String remoteAddr = request.getRemoteAddr();
        显示访问的ip地址
        System.out.println(remoteAddr);*/


        //1.获取请求路径URI
        final String requestURI = request.getRequestURI();
        //定义不需要拦截的路径
        String[] urls = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/sendMsg"
        };
        //2.判断请求是否需要处理
        boolean check = check(urls, requestURI);

        if(check){
            filterChain.doFilter(request, response);
            return;
        }

        //3.1判断登录状态
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(request, response);
            return;
        }

        //判断用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录！");

        //4.响应结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            return;
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
